#include <stdio.h>
#include <string.h>
#include <stdlib.h>


char * sample_itoa(int num, char * str, int radix)
{
	char *ptr = str;
	int i;
	int j;

	while (num) {
		*ptr++ = str[num % radix];
		num /= radix;

		if (num < radix) {
			*ptr++ = str[num];
			*ptr = '\0';
			break;
		}
	}

	j = ptr - str - 1;

	for (i = 0; i < (ptr - str) / 2; i++) {
		int temp = str[i];
		str[i] = str[j];
		str[j--] = temp;
	}

	return str;
}

void itoa(int value, char *str)
{
    if (value < 0)		// 如果是负数,则str[0]='-',并把value取反(变成正整数)

    {
        str[0] = '-';
        value = 0-value;
    }

    int i,j;

    for(i=1; value > 0; i++,value/=10)	// 从value[1]开始存放value的数字字符，不过是逆序，等下再反序过来

        str[i] = value%10+'0';			// 将数字加上0的ASCII值(即'0')就得到该数字的ASCII值

    for(j=i-1,i=1; j-i>=1; j--,i++)		// 将数字字符反序存放

    {
        str[i] = str[i]^str[j];
        str[j] = str[i]^str[j];
        str[i] = str[i]^str[j];
    }

    if(str[0] != '-')					// 如果不是负数，则需要把数字字符下标左移一位，即减1

    {
        for(i=0; str[i+1]!='\0'; i++)
            str[i] = str[i+1];
        str[i] = '\0';
    }
}

int main()
{
	int value = 100;
	char str[10] = { '\0' };

	itoa(value, str);
	printf("The result is:%s	len = %d\n", str, strlen(str));	// 100, 3

	sprintf(str, "%d", 100);
	printf("The result is:%s	len = %d\n", str, strlen(str));	// 100, 3

	sprintf(str, "0x%x", 100);
	printf("The result is:%s	len = %d\n", str, strlen(str));	// 0x64, 4	


	return 0;
}


